<!-- 考核事项 -->
<script lang="ts">
export default {
  name: "incomingOder"
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import {
  VXETable,
  VxeTableInstance,
  VxeFormPropTypes,
  VxeFormInstance,
  VxeTablePropTypes
} from "vxe-table";
import {
  queryInspectionIntoPage,
  addInspectionInto,
  deleteInspectionIntoById,
  queryInspectionIntoById,
  queryInspectionIntoListSelect,
  updateInspectionInto
} from "/@/api/quality/examineAssess";
import { successMessage, errorMessage } from "/@/utils/message";
import { useRoute } from "vue-router";
const route = useRoute();
const routeName = route.name as string;
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const procedure = reactive({
  radValue: 0,
  loading: false,
  submitLoading: false,
  filterName: "",
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  goodUnitData: [] as any[],
  formData: {
    code: "",
    id: 0,
    name: "",
    nlms: "",
    inspectionItemsList: [],
    isCalculate: 0,
    valueField: ""
  },
  formRules: {
    code: [{ required: true, message: "请输入考核事项编码" }],
    name: [{ required: true, message: "请输入考核事项名称" }],
    nlms: [{ required: true, message: "请输入计算公式" }],
    valueField: [{ required: true, message: "请输入取值字段" }]
  } as VxeFormPropTypes.Rules,
  state: "新增",
  security: [
    { label: "是", value: "1" },
    { label: "否", value: "0" }
  ]
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    code: "",
    name: ""
  }
});

const xTable = ref({} as VxeTableInstance);
const xForm = ref({} as VxeFormInstance);
// 查询
const searchEvent = () => {
  const data: any = {};
  data.code = table.listQuery.code;
  data.name = table.listQuery.name;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  procedure.loading = true;
  Object.assign(data, table.listQuery);
  queryInspectionIntoPage(data).then((res: any) => {
    if (res.code === 0) {
      procedure.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    procedure.loading = false;
  });
};

// 新增质检模板=检验规范
const addRepair = () => {
  procedure.formData.inspectionItemsList.push({
    inspectionIntoId: ""
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
//编辑
const editEvent = (row: any) => {
  procedure.state = "编辑";
  Object.keys(procedure.formData).forEach(key => {
    procedure.formData[key] = row[key];
  });
  queryInspectionIntoById(row.id).then((res: any) => {
    procedure.formData.inspectionItemsList = res.data.inspectionItemsList;
  });
  procedure.selectRow = row;
  procedure.showEdit = true;
};
// 新增
const insertEvent = () => {
  procedure.state = "新增";
  procedure.selectRow = null;
  procedure.showEdit = true;
};
const radBtn = v => {
  procedure.radValue = v.label;
};
// 表单提交
const submitEvent = async () => {
  const $table = xTable.value;
  const $form = xForm.value;
  const errMap = await $form.validate();
  if (!errMap) {
    procedure.submitLoading = true;
    if (procedure.selectRow) {
      // 修改
      updateInspectionInto(procedure.formData)
        .then((res: any) => {
          if (res.code === 0) {
            successMessage("操作成功");
            handleClose();
            searchEvent();
          } else {
            errorMessage(res.message);
            procedure.submitLoading = false;
          }
        })
        .catch(() => {
          errorMessage("操作失败");
          procedure.submitLoading = false;
        });
    } else {
      // 新增
      addInspectionInto(procedure.formData)
        .then((res: any) => {
          if (res.code === 0) {
            searchEvent();
            successMessage("操作成功");
            procedure.showEdit = false;
            handleClose();
          } else {
            errorMessage(res.message);
          }
          procedure.submitLoading = false;
        })
        .catch(() => {
          errorMessage("操作失败");
          procedure.submitLoading = false;
        });
    }
  }
};
// 删除
const deleteEvent = async (row: any) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    const $table = xTable.value;
    $table.remove(row);
    deleteInspectionIntoById(row.id).then((res: any) => {
      if (res.code === 0) {
        successMessage("删除成功");
      } else {
        errorMessage(res.message);
      }
    });
  }
};
// 删除检查项目
const deleteItem = item => {
  const index = procedure.formData.inspectionItemsList.indexOf(item);
  if (index !== -1) {
    procedure.formData.inspectionItemsList.splice(index, 1);
  }
};
// 获取考核事项列表
const queryUnit = () => {
  queryInspectionIntoListSelect().then((res: any) => {
    procedure.goodUnitData = res.data;
  });
};
const cellClassName: VxeTablePropTypes.CellClassName = ({ row, column }) => {
  if (column.property === "isEnabled") {
    if (row.isEnabled == 0) {
      return "col-orange";
    } else {
      return "col-blue";
    }
  }
  return null;
};
const handleClose = () => {
  // xForm.value.reset();
  (procedure.formData = {
    code: "",
    id: 0,
    name: "",
    nlms: "",
    inspectionItemsList: [],
    isCalculate: 0,
    valueField: ""
  }),
    nextTick(() => {
      procedure.submitLoading = false;
      procedure.showEdit = false;
      procedure.selectRow = null;
      procedure.state = "新增";
      procedure.formData.inspectionItemsList = [];
    });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    // const $table = xTable.value;
    searchEvent();
    queryUnit();
    table.tableHeight = changeHeight();
  });
});
</script>
<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="事项编码">
        <template #default="{ data }">
          <vxe-input
            v-model="data.code"
            placeholder="请输入事项编码"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="事项名称">
        <template #default="{ data }">
          <vxe-input
            v-model="data.name"
            placeholder="请输入事项名称"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            icon="fa fa-search"
            status="primary"
            @click="searchEvent"
            v-auth="routeName + ':search'"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-plus"
            status="primary"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
        </template>
      </vxe-form-item>
    </vxe-form>
    <vxe-table
      ref="xTable"
      class="mytable-style"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="procedure.tableData"
      :cell-class-name="cellClassName"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="code" title="考核事项编码"></vxe-column>
      <vxe-column field="name" title="考核事项名称"></vxe-column>
      <vxe-column field="createdBy" title="创建人"></vxe-column>
      <vxe-column field="createdTime" title="创建时间" min-width="100">
        <template #default="{ row }">
          {{ row.createdTime ? row.createdTime.split(" ")[0] : "" }}
        </template>
      </vxe-column>
      <!-- <vxe-column field="nlms" title="计算公式"></vxe-column> -->
      <!-- <vxe-column field="assessment" title="考核依据"></vxe-column> -->
      <vxe-column title="操作" width="200">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="editEvent(row)"
            v-auth="routeName + ':edit'"
            >编辑</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-trash-o"
            @click="deleteEvent(row)"
            v-auth="routeName + ':delete'"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 表单弹框 -->
    <vxe-modal
      v-model="procedure.showEdit"
      :title="procedure.selectRow ? '查看详情' : '新增&保存'"
      width="80%"
      min-width="700"
      min-height="800"
      :loading="procedure.submitLoading"
      resize
      showFooter
      destroy-on-close
      @close="handleClose"
    >
      <template #default>
        <vxe-form
          ref="xForm"
          :data="procedure.formData"
          :rules="procedure.formRules"
          title-align="right"
          title-width="120"
        >
          <vxe-form-item
            field="code"
            title="考核事项编码"
            :span="11"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.code"
                placeholder="请输入考核事项编码"
                :disabled="procedure.selectRow ? true : false"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="name"
            title="考核事项名称"
            :span="12"
            :item-render="{}"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.name"
                placeholder="请输入考核事项名称"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <template
            v-for="item in procedure.formData.inspectionItemsList"
            :key="item.id"
          >
            <vxe-form-item field="name" title="考核指标" :span="16">
              <template #default>
                <vxe-input
                  v-model="item.name"
                  placeholder="请输入考核指标"
                ></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item :span="4">
              <template #default>
                <el-button type="danger" size="small" @click="deleteItem(item)"
                  >删除</el-button
                >
              </template>
            </vxe-form-item>
          </template>
          <vxe-form-item :span="24">
            <template #default>
              <!-- v-if="procedure.selectRow == '新增&保存'" -->
              <el-button
                type="primary"
                style="margin-left: 120px"
                size="small"
                @click="addRepair"
                >添加</el-button
              >
            </template>
          </vxe-form-item>
          <vxe-form-item field="isEnabled" title="是否需要计算" :span="5">
            <template #default="{ data }">
              <vxe-radio-group v-model="data.isCalculate" @change="radBtn">
                <vxe-radio :label="1" content="是"></vxe-radio>
                <vxe-radio :label="0" content="否"></vxe-radio>
              </vxe-radio-group>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="nlms"
            title="计算公式"
            :span="8"
            :item-render="{}"
            v-if="procedure.radValue == 1"
          >
            <template #default="{ data }">
              <vxe-input
                v-if="procedure.radValue == 1"
                v-model="data.nlms"
                placeholder="请输入计算公式"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item
            field="valueField"
            title="取值字段"
            :span="8"
            :item-render="{}"
            v-if="procedure.radValue == 0"
          >
            <template #default="{ data }">
              <vxe-input
                v-model="data.valueField"
                placeholder="请输入取值字段"
                v-if="procedure.radValue == 0"
              ></vxe-input>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #footer>
        <vxe-button @click="handleClose">取 消</vxe-button>
        <vxe-button status="primary" @click="submitEvent">确 定</vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>

<style scoped>
/* @import url("/@/style/dialog.css"); */
.mytable-style .vxe-body--column.col-blue {
  background-color: #60b8ff;
  color: #fff;
}
.mytable-style .vxe-body--column.col-orange {
  background-color: #f56c6c;
  color: #fff;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
</style>
